package com.xhsj.user.event;

import com.google.common.collect.Maps;
import com.xhsj.user.hr.process.message.service.TbProjectMessageService;
import com.xhsj.user.utils.AliyunMessage;
import com.xhsj.user.utils.Message;
import com.xhsj.user.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @author suxiaolin
 * @date 2020/6/23 11:23
 */
@Slf4j
public class MessageHandleThread implements Runnable {
    @Override
    public void run() {
        while (true){
            synchronized(String.class){
                try {
                    Map<String, String> poll = TbProjectMessageService.queue.take();

                    log.info("线程{}消费,手机号:{},模块名:{},发送人:{},发送次数:{}",Thread.currentThread().getName(),poll.get("phone"),poll.get("moudleName"),poll.get("name"),poll.get("count"));
                    Integer count = StringUtils.toInteger(poll.get("count"));
                    if (count != 3) {
                        try {
                            System.err.println(Thread.currentThread().getName());
                            Thread.sleep(3000);
                            reSendMessage(poll.get("phone"), poll.get("moudleName"),count+1,poll.get("name"));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void reSendMessage(String phone, String moudleName, int count,String name) {
        Message message = AliyunMessage.sendSms(phone, moudleName,name);
        String code = String.valueOf(message.get("code"));
        if ("1".equals(code)) {// 发送失败
            Map<String, String> map = Maps.newHashMap();
            map.put("phone",phone);
            map.put("moudleName",moudleName);
            map.put("count",String.valueOf(count));
            map.put("name",name);
            try {
                TbProjectMessageService.queue.put(map);
            } catch (InterruptedException e) {
                log.error("队列添加出错",e);
            }
        }
    }
}
